<?php
/**
 * Created by PhpStorm.
 * User: lenovo-7
 * Date: 2015/6/12
 * Time: 9:34
 */
//require(INMAN_API_DIR.'base.php');
class inman_api_user extends inman_api_base{
    /**
     * 1.1登录
     * @params string $username 用户名 | 手机号 | 邮箱
     * @params string $password 密码
     */

    public function login($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        $pamData = app::get('pam')->model('members')->getRow('password_account,createtime',array('login_account'=>$params['username']));
        $use_pass_data['login_name'] = $pamData['password_account'];
        $use_pass_data['createtime'] = $pamData['createtime'];
        $params['password'] = pam_encrypt::get_encrypted_password(trim($params['password']),'member',$use_pass_data);
        $filter = array('login_account'=>$params['username'],'login_password'=>$params['password']);
        $account = app::get('pam')->model('members')->getList('*',$filter);
        if(!$account){
            $error['status'] = 'false';
            $error['message'] = app::get('pam')->_('用户名或密码错误');
            return $error;
        }else{
            $b2c_members_model = app::get('b2c')->model('members');
            $member_id = $account[0]['member_id'];
            $member_data = $b2c_members_model->getList( '*', array('member_id'=>$member_id) );
            if( !$member_data ){
                $error['status'] = 'false';
                $error['message'] = app::get('b2c')->_('登录失败：会员数据存在问题,请联系商家或客服');
                return $error;
            }

            $member_data = $member_data[0];
            $member_data['order_num'] = app::get('b2c')->model('orders')->count( array('member_id'=>$member_id) );

            if(app::get('b2c')->getConf('site.level_switch')==1)
            {
                $member_data['member_lv_id'] = $b2c_members_model->member_lv_chk($member_data['member_lv_id'],$member_data['experience']);
            }
            if(app::get('b2c')->getConf('site.level_switch')==0)
            {
                $member_point_model = app::get('b2c')->model('member_point');
                $member_data['member_lv_id'] = $member_point_model->member_lv_chk($member_id,$member_data['member_lv_id'],$member_data['point']);
            }
            $b2c_members_model->update($member_data,array('member_id'=>$member_id));
        }
        $db = kernel::database();
        $next_rank_integral = $db->selectrow('select point from sdb_b2c_member_lv where member_lv_id = '.($member_data['member_lv_id']+1));
        $next_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id = '.($member_data['member_lv_id']+1));
        $user_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id='.$member_data['member_lv_id']);
        $data['sid'] = $this->set_sid($member_id);
        $data['user_id'] = $account[0]['member_id'];
        $data['user_name'] = $account[0]['login_account'];
        $data['user_avatar'] = $member_data['user_avatar'];
        $data['user_integral'] = $member_data['point'];
        $data['user_rank'] = $member_data['member_lv_id'];
        $data['user_rank_desc'] = !$next_rank_name?'您目前是：['.$user_rank_name['name'].'].':'您目前是：['.$user_rank_name['name'].']（积分累积到'.$next_rank_integral['point'].'可成为'.$next_rank_name['name'].'）';
        $data['is_union'] = false;
        $data['is_bind'] = !empty($member_data['mobile']);
        $data['bind_number'] = empty($member_data['mobile'])?'':$member_data['mobile'];
        $data['is_pass'] = false;

        kernel::single('b2c_user_object')->set_member_session($member_id);
        return $data;
    }

    /**
     * 1.2个人信息
     */
    public function getInfo($params,&$service){
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $db = kernel::database();
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $member_name = kernel::single('b2c_user_object')->get_member_name();
        $memberData = app::get('b2c')->model('members')->getRow( '*', array('member_id'=>$member_id) );

        $shopping_cart_num = $db->count('select * from sdb_b2c_cart_objects where member_id='.$member_id);
        $nopay_order_num = $db->count('select *  from sdb_b2c_orders where member_id='.$member_id.' and pay_status="0"');
        $norec_order_num = $db->count('select * from sdb_b2c_orders where member_id='.$member_id.' and status="active"');
        $nocomment_goods_num = $db->count('select * from sdb_b2c_orders  where member_id='.$member_id.' and order_id not in (select order_id from sdb_b2c_member_comments where object_type="discuss" and order_id is not null)');
        $unshipped_order = $db->count('select * from sdb_b2c_orders where member_id='.$member_id.' and ship_status="0"');
        $returned_order = $db->count('select * from sdb_b2c_orders where member_id='.$member_id.' and ship_status in ("3","4")');
        $vouchers_number = $db->count('select * from sdb_b2c_member_coupon where member_id='.$member_id);
        $start_rank_integral = $db->selectrow('select point from sdb_b2c_member_lv where member_lv_id = '.$memberData['member_lv_id']);
        $next_rank_integral = $db->selectrow('select point from sdb_b2c_member_lv where member_lv_id = '.($memberData['member_lv_id']+1));
        $next_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id = '.($member_data['member_lv_id']+1));
        $user_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id='.$memberData['member_lv_id']);

        $return['user_id'] = intval($memberData['member_id']);
        $return['user_name'] = $member_name;
        $return['user_avatar'] = $memberData['user_avatar'];
        $return['user_avatar_original'] = $memberData['user_avatar'];
        $return['email'] = $memberData['email'];
        $return['birthday'] = $memberData['b_year'].'-'.$memberData['b_month'].'-'.$memberData['b_day'];
        $return['user_integral'] = $memberData['point'];
        $return['user_rank'] = $memberData['member_lv_id'];
        $return['user_rank_desc'] = !$next_rank_name?'您目前是：['.$user_rank_name['name'].'].':'您目前是：['.$user_rank_name['name'].']（积分累积到'.$next_rank_integral['point'].'可成为'.$next_rank_name['name'].'）';
        $return['start_rank_integral'] = $start_rank_integral['point'];
        $return['next_rank_integral'] = $next_rank_integral['point'];
        $return['shopping_cart_num'] = $shopping_cart_num;
        $return['nopay_order_num'] = $nopay_order_num;
        $return['norec_order_num'] = $norec_order_num;
        $return['nocomment_goods_num'] = $nocomment_goods_num;
        $return['unpaid_order'] = $nopay_order_num;
        $return['unshipped_order'] = $unshipped_order;
        $return['unreceived_order'] = $norec_order_num;
        $return['uncommented_order'] = $nocomment_goods_num;
        $return['returned_order'] = $returned_order;
        $return['user_rank_url'] = 'http:\/\/121.9.227.70:8085\/About\/rank.html';
        $return['is_union'] = false;
        $return['is_bind'] = !empty($memberData['mobile']);
        $return['bind_number'] = empty($memberData['mobile'])?'':$memberData['mobile'];
        $return['is_pass'] = false;
        $return['vouchers_number'] = $vouchers_number;
        $return['is_yinyuejia'] = '????';
        $return['is_distribution_store_user'] = '????';
        $return['is_distribution_user'] = '????';
        $return['has_new_order'] = '????';
        return $return;
    }

    /**
     * 1.3修改密码
     */
    public function changePwd($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();

        $pamMembersModel = app::get('pam')->model('members');
        $pamData = $pamMembersModel->getList('password_account,createtime,login_password',array('member_id'=>$member_id));
        $use_pass_data['login_name'] = $pamData[0]['password_account'];
        $use_pass_data['createtime'] = $pamData[0]['createtime'];
        $params['oldpwd'] = pam_encrypt::get_encrypted_password(trim($params['oldpwd']),'member',$use_pass_data);

        if( empty($params['oldpwd']) || $params['oldpwd'] !== $pamData[0]['login_password'] ){
            $msg = app::get('b2c')->_('输入的旧密码与原密码不符！');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }

        if( empty($params['newpwd']) ){
            return $service->send_user_error('参数错误，修改的新密码不能为空');
        }

        $userPassport = kernel::single('b2c_user_passport');
        if( !$userPassport->check_passport($params['newpwd'],$params['newpwd'],$msg) ){
            return $service->send_user_error($msg);
        }

        $db = kernel::database();
        $db->beginTransaction();
        $params['newpwd'] = pam_encrypt::get_encrypted_password(trim($params['newpwd']),'member',$use_pass_data);
        foreach($pamData as $row){
            if(!$pamMembersModel->update(array('login_password'=>$params['newpwd']),array('member_id'=>$member_id))){
                $db->rollBack();
                $error['status'] = 'false';
                $error['message'] = '密码修改失败';
                return $error;
            }
        }
        $db->commit();
        $return['error_code']=0;
        return $return;
    }

    /**
     * 1.4	忘记密码-发送验证码
     */
    public function findSendVerify($params,&$service){
        $userPassport = kernel::single('b2c_user_passport');
        $login_type = $userPassport->get_login_account_type($params['phone']);
        if($login_type != 'mobile'){
            $msg = app::get('b2c')->_('请填写正确的手机号码');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }

        if( !$userPassport->is_exists_login_name($params['phone'])){
            $msg = app::get('b2c')->_('系统不存在该账号，请重新输入');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }

        $data = $this->send_sms($params['phone'],'forgot',$msg);
        if( !$data ){
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        kernel::single("base_session")->start();
        $return['sid']=kernel::single("base_session")->sess_id();
        $return['vcode'] = $data['vcode'];
        $_SESSION['forgot_passwd']['vcode'] = $data['vcode'];
        $_SESSION['forgot_passwd']['user_id'] = app::get('pam')->model('members')->getRow('member_id',array('login_account'=>$params['phone']));
        $_SESSION['forgot_passwd']['is_check'] = 0;
        return $return;
    }

    /**
     * 1.5 忘记密码-检查验证码
     */
    public function findCheckVerify($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        $_GET['sess_id'] = $params['sid'];
        kernel::single("base_session")->start();
        $vcode = $_SESSION['forgot_passwd']['vcode'];
        if(!$vcode){
            $msg = app::get('b2c')->_('sid不正确或验证码过期');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        if($_SESSION['forgot_passwd']['is_check'] == 1){
            $msg = app::get('b2c')->_('已通过验证，无须重复操作');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        if($params['verify'] != $vcode ){
            $msg = app::get('b2c')->_('短信验证错误');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $_SESSION['forgot_passwd']['is_check'] = 1;
        $return['error_code'] = 0;
        return $return;
    }

    /**
     * 1.6 忘记密码-重置密码
     */
    public function resetPassword($params,&$service){
        $_GET['sess_id'] = $params['sid'];
        kernel::single("base_session")->start();
        $user_id = $_SESSION['forgot_passwd']['user_id'];
        if( !$user_id ){
            $msg = app::get('b2c')->_('sid不正确或已过期');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $is_check = $_SESSION['forgot_passwd']['is_check'];
        if($is_check != 1){
            $msg = app::get('b2c')->_('验证未通过');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $login_password = $params['password'];
        if( !$login_password ){
            return $service->send_user_error('参数错误,密码不能为空');
        }

        $userPassport = kernel::single('b2c_user_passport');
        if( !$userPassport->check_passport($params['password'],$params['password'],$msg) ){
            return $service->send_user_error($msg);
        }

        $pamMembersModel = app::get('pam')->model('members');
        $pamData = $pamMembersModel->getList('password_account,createtime,login_password',array('member_id'=>$user_id));
        $use_pass_data['login_name'] = $pamData[0]['password_account'];
        $use_pass_data['createtime'] = $pamData[0]['createtime'];
        $login_password = pam_encrypt::get_encrypted_password(trim($params['password']),'member',$use_pass_data);

        $pamMembersModel = app::get('pam')->model('members');
        $db = kernel::database();
        $db->beginTransaction();
        if(!$pamMembersModel->update(array('login_password'=>$login_password),array('member_id'=>$user_id))){
            $db->rollBack();
            $msg = app::get('b2c')->_('密码修改失败');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $db->commit();
        kernel::single("base_session")->destory();

        $account = $pamMembersModel->getList('*',array('member_id'=>$user_id));
        $member_data = app::get('b2c')->model('members')->getRow( '*', array('member_id'=>$user_id) );
        $next_rank_integral = $db->selectrow('select point from sdb_b2c_member_lv where member_lv_id = '.($member_data['member_lv_id']+1));
        $next_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id = '.($member_data['member_lv_id']+1));
        $user_rank_name = $db->selectrow('select name from sdb_b2c_member_lv where member_lv_id='.$member_data['member_lv_id']);
        unset($_GET['sess_id']);
        $data['sid'] = $this->set_sid($user_id);
        $data['user_id'] = $account[0]['member_id'];
        $data['user_name'] = $account[0]['login_account'];
        $data['user_avatar'] = $member_data['user_avatar'];
        $data['user_integral'] = $member_data['point'];
        $data['user_rank'] = $member_data['member_lv_id'];
        $data['user_rank_desc'] = !$next_rank_name?'您目前是：['.$user_rank_name['name'].'].':'您目前是：['.$user_rank_name['name'].']（积分累积到'.$next_rank_integral['point'].'可成为'.$next_rank_name['name'].'）';
        $data['is_union'] = false;
        $data['is_bind'] = !empty($member_data['mobile']);
        $data['bind_number'] = empty($member_data['mobile'])?'':$member_data['mobile'];
        $data['is_pass'] = false;

        kernel::single('b2c_user_object')->set_member_session($user_id);
        return $data;

    }

    /**
     * 1.15 更新信息
     */
    public function updateInfo($params,&$service){
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $b2c_member = app::get('b2c')->model('members');
        $member_info = $b2c_member->getRow('*',array('member_id'=>$member_id));

        $params['nickname'] && $member_info['name'] = $params['nickname'];
        $params['email'] && $member_info['email'] = $params['email'];
        $params['birthday'] && $member_info['birthday'] = $params['birthday'];

        $res = $b2c_member->edit($member_id,$member_info);
        $data = $res?0:1;

        return $data;
    }

    /**
     * 1.22 用户收藏商品列表
     */
    public function favorite($params,&$service){
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();

        $params['page_no'] = intval($params['page_no']) ? $params['page_no'] : 1;
        $params['page_num'] = intval($params['page_num']) ? $params['page_num'] : 5;

        $memberData = app::get('b2c')->model('members')->getRow('member_lv_id',array('member_id'=>$member_id));
        $aData = kernel::single('b2c_member_fav')->get_favorite($member_id,$memberData['member_lv_id'],$params['page_no'],$params['page_num']);
        $aProduct = $aData['data'];
        $i = 0;
        foreach($aProduct as $k=>$v){
            $favGoods[$i]['collect_id'] = $v['gnotify_id'];	//	收藏id
            $favGoods[$i]['goods_sn']   = intval($v['spec_desc_info'][0]['product_id']);	    //	商品编号（货品ID）

            $spec_info_arr = explode('、',$v['spec_desc_info'][0]['spec_info']);
            $color_arr = explode('：',$spec_info_arr[0]);
            $favGoods[$i]['color_code'] = $color_arr[1];	//	颜色编号

            $favGoods[$i]['shop_price'] = $v['price'];	//	商品价格
            $favGoods[$i]['add_time']   = $v['create_time'];	    //	收藏时间
            $favGoods[$i]['available_number'] = intval($v['spec_desc_info'][0]['store']);	//	可用库存
            $imageIds[$i] = $v['image_default_id'];
            $i++;
        }
        $imageData = $this->_get_gids_image($imageIds,array());
        foreach( (array)$favGoods as $key=>$row ){
            $favGoods[$key]['goods_img'] = $imageData[$key] ? $imageData[$key]['m_url'] : '';
        }

        $return['goods'] = $favGoods;
        $return['page'] = intval($aData['page']);

        return $return;
    }

    /**
     * 1.25 手机绑定-发送验证码
     */
    public function bindSendVerify($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        if( empty($params['phone']) ){
            return $service->send_user_error('参数错误，phone不能为空');
        }
        $userPassport = kernel::single('b2c_user_passport');
        $res = $userPassport->check_signup_account($params['phone'],$msg);
        if( !$res ){
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        if( $msg != 'mobile' ){
            $error['status'] = 'false';
            $error['message'] = app::get('b2c')->_('请填写正确的手机号码');
            return $error;
        }
        $data = $this->send_sms($params['phone'],'reset',$msg);
        if( !$data ){
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $new_sid = $this->set_sid($member_id);
        kernel::single("base_session")->set_sess_id($new_sid);
        $return['sid'] = $new_sid;
        $return['vcode'] = $data['vcode'];
        $_SESSION['user_bind']['vcode'] = $data['vcode'];
        $_SESSION['user_bind']['phone'] = $params['phone'];
        $_SESSION['user_bind']['user_id'] = $member_id;
        return $return;
    }

    /**
     * 1.26 手机绑定-检查验证码-完成绑定
     */
    public function bindCheckVerify($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        $_GET['sess_id'] = $params['sid'];
        kernel::single("base_session")->start();
        $vcode = $_SESSION['user_bind']['vcode'];
        $phone = $_SESSION['user_bind']['phone'];
        $member_id = $_SESSION['user_bind']['user_id'];
        if(!$member_id){
            return $service->send_user_error('100001','error sid');

        }
        if( empty($params['verify']) ){
            return $service->send_user_error('参数错误，verify不能为空');
        }else{
            $verify = $params['verify'];
        }

        if( $verify != $vcode ){
            $msg = app::get('b2c')->_('短信验证错误');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }

        $db = $db = kernel::database();
        $data = $db->exec('update sdb_b2c_members set mobile='.$phone.' where member_id='.$member_id);
        if($data) {
            $return['error_code'] = 0;
        }else{
            $return['error_code'] = 1;
            echo $data;
        }
        return $return;
    }

    /**
     * 1.30 取消手机绑定-发送验证码
     */
    public function cancelBindSendVerify($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $b2c_member = app::get(b2c)->model('members');
        $phone = $b2c_member->getRow('mobile',array('member_id'=>$member_id));

        $data = $this->send_sms($phone,'reset',$msg);
        if( !$data ){
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }

        $return['error_code'] = 0;
        $return['vcode'] = $data['vcode'];
        $_SESSION['user_cancel_bind']['vcode'] = $data['vcode'];
        return $return;
    }

    /**
     * 1.31 取消绑定-检查验证码
     */
    public function cancelBindCheckVerify($params,&$service){
        $params = utils::_filter_input($params);//过滤xss攻击
        if(!$this->check_sid($params['sid']) ){
            return $service->send_user_error('100001','error sid');
        }
        $member_id = kernel::single('b2c_user_object')->get_member_id();
        $vcode = $_SESSION['user_cancel_bind']['vcode'];
        if( empty($params['verify']) ){
            return $service->send_user_error('参数错误，verify不能为空');
        }else{
            $verify = $params['verify'];
        }
        if( $verify != $vcode ){
            $msg = app::get('b2c')->_('短信验证错误');
            $error['status'] = 'false';
            $error['message'] = $msg;
            return $error;
        }
        $db = $db = kernel::database();
        $data = $db->exec('update sdb_b2c_members set mobile="" where member_id='.$member_id);
        if($data) {
            $return['error_code'] = 0;
        }else{
            $return['error_code'] = 1;
            echo $data;
        }
        return $return;
    }
}